package com.cloud.client;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Objects;

public class DownloadResponseBody extends ResponseBody {

    private final Response originalResponse;
    private final ProgressListener progressListener;

    public DownloadResponseBody(Response originalResponse, ProgressListener progressListener){
        this.originalResponse = originalResponse;
        this.progressListener = progressListener;
    }

    @Override
    public long contentLength() {
        return Objects.requireNonNull(originalResponse.body()).contentLength();
    }

    @NotNull
    @Override
    public BufferedSource source() {
        return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
            private long bytesRead;
            @Override
            public long read(@NotNull Buffer sink, long byteCount) throws IOException {
                long readLength = super.read(sink, byteCount);
                bytesRead += readLength == -1 ? 0 : readLength;
                if (progressListener != null) {
                    progressListener.onProgress((double)bytesRead, (double)contentLength());
                }
                return readLength;
            }
        });
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return Objects.requireNonNull(originalResponse.body()).contentType();
    }
}
